import wiringpi as gpio
import time

d1 = 12
d2 = 13
d3 = 15
d4 = 16

all_d = [d1, d2, d3, d4]

a = 18
b = 19
c = 21
d = 22
e = 23
f = 24
g = 26
dp = 27

all_led = [a, b, c, d, e, f, g, dp]

display_map = {
    '0': [a, b, c, d, e, f],
    '1': [b, c],
    '2': [a, b, d, e, g],
    '3': [a, b, c, d, g],
    '4': [b, c, f, g],
    '5': [a, c, d, f, g],
    '6': [a, c, d, e, f, g],
    '7': [a, b, c],
    '8': [a, b, c, d, e, f, g],
    '9': [a, b, c, d, f, g]
}

def init():
    gpio.wiringPiSetupPhys()
    for d in all_d:
        gpio.pinMode(d, 1)
        gpio.digitalWrite(d, gpio.HIGH)
    for led in all_led:
        gpio.pinMode(led, 1)
        gpio.digitalWrite(led, gpio.LOW)

def close(pins = None):
    if pins:
        for pin in pins:
            if pin in all_d:
                gpio.digitalWrite(pin, gpio.LOW)
            if pin in all_led:
                gpio.digitalWrite(pin, gpio.HIGH)
    else:
        for d in all_d:
            gpio.digitalWrite(d, gpio.LOW)
    
        for led in all_led:
            gpio.digitalWrite(led, gpio.HIGH)


def display_num(num):
    t = type(num)
    if (t == float or t == int) and num < 100:
        n = str(num)[:5]
        nums = n.split('.')

        integer, decimal = '0', '0'
        if len(nums) == 1:
            integer = nums[0]
        else:
            integer, decimal = nums
        if len(integer) == 1:
            integer = '0' + integer
        if len(decimal) == 1:
            decimal += '0'
        close()
        i1 = integer[0]
        gpio.digitalWrite(d1, gpio.HIGH)
        for p in display_map[i1]:
            gpio.digitalWrite(p, gpio.LOW)
        gpio.delay(1)
        close()
        
        i2 = integer[1]
        gpio.digitalWrite(d2, gpio.HIGH)
        for p in display_map[i2]:
            gpio.digitalWrite(p, gpio.LOW)
        gpio.digitalWrite(dp, gpio.LOW)
        gpio.delay(1)
        close()

        dd1 = decimal[0]
        gpio.digitalWrite(d3, gpio.HIGH)
        for p in display_map[dd1]:
            gpio.digitalWrite(p, gpio.LOW)
        gpio.delay(1)
        close()

        dd2 = decimal[1]
        gpio.digitalWrite(d4, gpio.HIGH)
        for p in display_map[dd2]:
            gpio.digitalWrite(p, gpio.LOW)
        gpio.delay(1)
        close()
    else:
        close()

def display(t, num):
    t1 = gpio.millis()
    while True:
        display_num(num)
        if gpio.millis() - t1 > t:
            break


